package com.jdk.demo.mappedByteBuffer;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

/**执行速度测试
 * @author Ziroom
 *
 */
public class MmapSpeedTest {

	static int _4kb = 4 * 1024;
	static int _GB = 1024 * 1024 * 1024;

	public static void main(String[] args) throws Exception {
		//w1(new File("E:\\zsl\\111.txt"));
		//w2(new File("E:\\zsl\\111.txt"));
		w3(new File("E:\\zsl\\111.txt"));
	}

	public static void w1(File file) throws Exception {
		// 方法一: 4kb 刷盘
		FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();
		ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_4kb);
		for (int i = 0; i < _4kb; i++) {
		    byteBuffer.put((byte)0);
		}
		for (int i = 0; i < _GB; i += _4kb) {
		    byteBuffer.position(0);
		    byteBuffer.limit(_4kb);
		    fileChannel.write(byteBuffer);
		}
	}

	public static void w2(File file) throws Exception {
		// 方法二: 单字节刷盘
		FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();
		ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1);
		byteBuffer.put((byte)0);
		for (int i = 0; i < _GB; i ++) {
		    byteBuffer.position(0);
		    byteBuffer.limit(1);
		    fileChannel.write(byteBuffer);
		}
	}

	public static void w3(File file) throws Exception {
		FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();
		MappedByteBuffer map = fileChannel.map(MapMode.READ_WRITE, 0, _GB);
		for (int i = 0; i < _GB; i++) {
			map.put((byte)0);
		}
	}

}
